package com.fosun.spr.core.base;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.beanutils.BeanUtils;

import com.fosun.spr.core.base.model.CoBaseSrModel;
import com.fosun.spr.core.exception.ServiceException;
import com.fosun.spr.core.message.ResultCode;
import com.fosun.spr.core.utils.ExtBeanUtils;
 

/**
 * 业务逻辑Service基类
 * 
 * @author Chen Shiming 陈市明 # SprCore Feb 22, 2017
 */
public abstract class CoBaseService {
	public final static String IS_DELETED_N = "0";
	public final static String IS_DELETED_Y = "1";
	public static String CODE_ERR = "-1";

	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	protected Date getDate(String t) {
		try {			
			return SDF.parse(t);		
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(t+" convert to date error");
		}
	}
	protected String getDateString(Date d){	 
		return SDF.format(d);		
	}
	// private static final Logger logger =
	// Logger.getLogger(CoBaseService.class);

	protected void tagSuccess(CoBaseSrModel srModel) {
		if (srModel != null) {
			srModel.setErrcode("0");
			srModel.setErrmsg("ok");
		}
		// TOOD 如果为空则报错
	}

	protected void tagFailure(CoBaseSrModel srModel, String errCode,
			String errMsg) {
		// TODO 如果为空则报错，如果errocode为0也视为报错
		if (srModel != null) {
			srModel.setErrcode(errCode);
			srModel.setErrmsg(errMsg);
		}
	}

	@SuppressWarnings("rawtypes")
	protected static void cglibCopyProperties(Class sClass, Class tClass,
			Object source, Object target, boolean useConverter) {

		ExtBeanUtils.cglibCopyProperties(sClass, tClass, source, target,
				useConverter);
	}
	@SuppressWarnings("rawtypes")
	protected static void cglibCopyProperties(
			Object source, Object target, boolean useConverter) {
		ExtBeanUtils.cglibCopyProperties(source.getClass(), target.getClass(), source, target,
				useConverter);
	}
	@SuppressWarnings("rawtypes")
	protected static <T> List<T> cglibCopyPropertiesList(Class sClass,
			Class tClass, Object sourceList, boolean useConverter) {

		return ExtBeanUtils.cglibCopyPropertiesList(sClass, tClass, sourceList,
				useConverter);
	}
	protected static String[] getArrayFromList(List list,String propertyName){
		String[] ids = new String[list.size()];
		try{
			for(int i=0,j=list.size();i<j;i++){
				Object obj = list.get(i);
				ids[i] = BeanUtils.getProperty(obj, propertyName);
			}	
		}catch(Exception e){
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
		return ids;
	}
	
	public static String getUuid(){
		return System.currentTimeMillis()+"-"+UUID.randomUUID().toString();
	}
}
